

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Furienson
 */
public class ListAnuncios {
   public ArrayList<Anuncio> anuncios = new ArrayList<Anuncio>();
    
    public int getAnuncios() throws SQLException{
        anuncios.clear();
         // JDBC driver name and database URL
      final String JDBC_DRIVER="com.mysql.jdbc.Driver";  
      final String DB_URL="jdbc:mysql://localhost:3306/java";

      //  Database credentials
      final String USER = "root";
      final String PASS = "";
      int countElements=0;
      Connection conn = null;
      Statement stmt= null;
      ResultSet rs= null;
       try{
         // Register JDBC driver
         Class.forName(JDBC_DRIVER);
         
         conn = DriverManager.getConnection(DB_URL,USER,PASS);
         stmt = conn.createStatement();
         rs = stmt.executeQuery("SELECT * FROM anuncios");
        while(rs.next()){
            Anuncio a = new Anuncio();
            a.setId(rs.getInt("id"));
            a.setPrecio(rs.getFloat("precio"));
            a.setTitulo(rs.getString("titulo"));
            a.setTexto(rs.getString("texto"));
            a.setVendido(rs.getBoolean("vendido"));
            anuncios.add(a);
            countElements++;
        }
        rs.close();
        stmt.close();
        conn.close();
        }catch (ClassNotFoundException ex) { 
            Logger.getLogger(Anuncio.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Anuncio.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalStateException ex) {
            Logger.getLogger(Anuncio.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
         if(conn!=null){
           conn.close();
         }
         if(rs!=null){
           rs.close();
         }
         if(stmt!=null){
           stmt.close();
         }
       }
       return countElements;
    }
}
